import React, { useState, useEffect } from 'react';
import { Card, Avatar, Tabs, Form, Input, Button, Row, Col, Divider, message, Descriptions, Statistic } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined, TeamOutlined, BankOutlined, EditOutlined, SaveOutlined, LineChartOutlined } from '@ant-design/icons';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

// 引入API
import { getUserInfo, updateUserInfo, updatePassword } from '../../../api/user';
import { getAttendanceHistory } from '../../../api/attendance';
import { getDepartments } from '../../../api/department';

// 引入样式
import './index.css';

const { TabPane } = Tabs;

const Profile = () => {
    const [editMode, setEditMode] = useState(false);
    const [loading, setLoading] = useState(false);
    const [userData, setUserData] = useState({});
    const [attendanceData, setAttendanceData] = useState([]);
    const [form] = Form.useForm();
    
    // 获取用户信息
    useEffect(() => {
        fetchUserInfo();
        fetchAttendanceData();
    }, []);
    
    // 获取用户信息
    const fetchUserInfo = async () => {
        try {
            setLoading(true);
            const [userResponse, departmentsResponse] = await Promise.all([
                getUserInfo(),
                getDepartments()
            ]);
            const user = userResponse.data || {};
            const departments = departmentsResponse.data || [];
            
            // 确保从employee中获取姓名和部门信息
            if (user.employee) {
                // 根据部门ID查找部门名称
                const department = departments.find(dept => dept.id === user.employee.departmentId);
                setUserData({
                    ...user,
                    name: user.employee.name || user.username,
                    department: department ? department.name : '未分配',
                    position: user.employee.position || '未分配',
                    entryDate: user.employee.hireDate || '未设置'
                });
            } else {
                // 如果没有employee信息，显示基本用户信息
                setUserData({
                    ...user,
                    name: user.username,
                    department: '未分配',
                    position: '未分配',
                    entryDate: '未设置'
                });
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            message.error('获取用户信息失败');
        } finally {
            setLoading(false);
        }
    };
    
    // 获取考勤数据
    const fetchAttendanceData = async () => {
        try {
            // 获取当前年份的开始和结束日期
            const now = new Date();
            const startOfYear = new Date(now.getFullYear(), 0, 1);
            const endOfYear = new Date(now.getFullYear(), 11, 31);
            
            const params = {
                startDate: startOfYear.toISOString().split('T')[0],
                endDate: endOfYear.toISOString().split('T')[0],
                statistics: true
            };
            
            const response = await getAttendanceHistory(params);
            
            if (response.monthlyStats) {
                // 转换后端统计数据为图表所需格式
                const monthlyData = response.monthlyStats.map(item => ({
                    month: `${item.month}月`,
                    attendance: item.normal || 0,
                    late: item.late || 0,
                    leave: item.leave || 0,
                    absent: item.absent || 0
                }));
                setAttendanceData(monthlyData);
            } else {
                // 如果没有数据，设置默认数据
                const defaultData = [
                    { month: '1月', attendance: 0, late: 0, leave: 0, absent: 0 },
                    { month: '2月', attendance: 0, late: 0, leave: 0, absent: 0 },
                    { month: '3月', attendance: 0, late: 0, leave: 0, absent: 0 },
                    { month: '4月', attendance: 0, late: 0, leave: 0, absent: 0 },
                    { month: '5月', attendance: 0, late: 0, leave: 0, absent: 0 },
                    { month: '6月', attendance: 0, late: 0, leave: 0, absent: 0 },
                ];
                setAttendanceData(defaultData);
            }
        } catch (error) {
            console.error('获取考勤数据失败:', error);
            message.error('获取考勤数据失败');
            // 设置默认数据
            const defaultData = [
                { month: '1月', attendance: 0, late: 0, leave: 0, absent: 0 },
                { month: '2月', attendance: 0, late: 0, leave: 0, absent: 0 },
                { month: '3月', attendance: 0, late: 0, leave: 0, absent: 0 },
                { month: '4月', attendance: 0, late: 0, leave: 0, absent: 0 },
                { month: '5月', attendance: 0, late: 0, leave: 0, absent: 0 },
                { month: '6月', attendance: 0, late: 0, leave: 0, absent: 0 },
            ];
            setAttendanceData(defaultData);
        }
    };

    // 处理个人信息表单提交
    const handleProfileSubmit = async (values) => {
        try {
            setLoading(true);
            await updateUserInfo(values);
            message.success('个人信息更新成功');
            setEditMode(false);
            // 重新获取用户信息
            fetchUserInfo();
        } catch (error) {
            console.error('更新个人信息失败:', error);
            message.error('更新个人信息失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理密码修改表单提交
    const handlePasswordSubmit = async (values) => {
        try {
            setLoading(true);
            await updatePassword(values);
            message.success('密码修改成功');
            // 清空表单
            form.resetFields();
        } catch (error) {
            console.error('修改密码失败:', error);
            message.error('修改密码失败');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="profile-container">
            <Row gutter={[24, 24]}>
                {/* 个人信息卡片 */}
                <Col xs={24} lg={8}>
                    <Card
                        bordered={false}
                        style={{ textAlign: 'center', height: '100%' }}
                        actions={[
                            <Button 
                                type="link" 
                                icon={editMode ? <SaveOutlined /> : <EditOutlined />}
                                onClick={() => setEditMode(!editMode)}
                            >
                                {editMode ? '保存' : '编辑'}
                            </Button>
                        ]}
                    >
                        <Avatar 
                            size={100} 
                            icon={<UserOutlined />} 
                            src={userData.avatar}
                            style={{ marginBottom: 20 }}
                        />
                        <h2>{userData.name}</h2>
                        <p>{userData.position}</p>
                        <p>{userData.department}</p>
                        <Divider />
                        <Descriptions column={1} size="small">
                            <Descriptions.Item label="邮箱">
                                <MailOutlined style={{ marginRight: 8 }} />
                                {userData.email}
                            </Descriptions.Item>
                            <Descriptions.Item label="电话">
                                <PhoneOutlined style={{ marginRight: 8 }} />
                                {userData.phone}
                            </Descriptions.Item>
                            <Descriptions.Item label="入职日期">
                                {userData.entryDate}
                            </Descriptions.Item>
                            <Descriptions.Item label="上次登录">
                                {userData.lastLogin}
                            </Descriptions.Item>
                        </Descriptions>
                    </Card>
                </Col>

                {/* 主要内容区 */}
                <Col xs={24} lg={16}>
                    <Card bordered={false}>
                        <Tabs defaultActiveKey="info">
                            {/* 个人信息标签页 */}
                            <TabPane tab="个人信息" key="info">
                                {editMode ? (
                                    <Form
                                        layout="vertical"
                                        initialValues={{
                                            name: userData.name,
                                            email: userData.email,
                                            phone: userData.phone,
                                            department: userData.department,
                                            position: userData.position
                                        }}
                                        onFinish={handleProfileSubmit}
                                    >
                                        <Form.Item
                                            name="name"
                                            label="姓名"
                                            rules={[{ required: true, message: '请输入姓名' }]}
                                        >
                                            <Input prefix={<UserOutlined />} placeholder="姓名" />
                                        </Form.Item>
                                        <Form.Item
                                            name="email"
                                            label="邮箱"
                                            rules={[
                                                { required: true, message: '请输入邮箱' },
                                                { type: 'email', message: '请输入有效的邮箱地址' }
                                            ]}
                                        >
                                            <Input prefix={<MailOutlined />} placeholder="邮箱" />
                                        </Form.Item>
                                        <Form.Item
                                            name="phone"
                                            label="电话"
                                            rules={[
                                                { required: true, message: '请输入电话' },
                                                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                                            ]}
                                        >
                                            <Input prefix={<PhoneOutlined />} placeholder="电话" />
                                        </Form.Item>
                                        <Form.Item
                                            name="department"
                                            label="部门"
                                            rules={[{ required: true, message: '请输入部门' }]}
                                        >
                                            <Input prefix={<TeamOutlined />} placeholder="部门" />
                                        </Form.Item>
                                        <Form.Item
                                            name="position"
                                            label="职位"
                                            rules={[{ required: true, message: '请输入职位' }]}
                                        >
                                            <Input prefix={<BankOutlined />} placeholder="职位" />
                                        </Form.Item>
                                        <Form.Item>
                                            <Button type="primary" htmlType="submit" loading={loading}>
                                                保存
                                            </Button>
                                        </Form.Item>
                                    </Form>
                                ) : (
                                    <Descriptions bordered column={{ xs: 1, sm: 2 }}>
                                        <Descriptions.Item label="姓名">{userData.name}</Descriptions.Item>
                                        <Descriptions.Item label="邮箱">{userData.email}</Descriptions.Item>
                                        <Descriptions.Item label="电话">{userData.phone}</Descriptions.Item>
                                        <Descriptions.Item label="部门">{userData.department}</Descriptions.Item>
                                        <Descriptions.Item label="职位">{userData.position}</Descriptions.Item>
                                        <Descriptions.Item label="入职日期">{userData.entryDate}</Descriptions.Item>
                                    </Descriptions>
                                )}
                            </TabPane>

                            {/* 密码修改标签页 */}
                            <TabPane tab="密码修改" key="password">
                                <Form
                                    layout="vertical"
                                    onFinish={handlePasswordSubmit}
                                    form={form}
                                >
                                    <Form.Item
                                        name="oldPassword"
                                        label="旧密码"
                                        rules={[{ required: true, message: '请输入旧密码' }]}
                                    >
                                        <Input.Password prefix={<LockOutlined />} placeholder="旧密码" />
                                    </Form.Item>
                                    <Form.Item
                                        name="newPassword"
                                        label="新密码"
                                        rules={[
                                            { required: true, message: '请输入新密码' },
                                            { min: 6, message: '密码长度不能少于6个字符' }
                                        ]}
                                    >
                                        <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
                                    </Form.Item>
                                    <Form.Item
                                        name="confirmPassword"
                                        label="确认密码"
                                        dependencies={['newPassword']}
                                        rules={[
                                            { required: true, message: '请确认新密码' },
                                            ({ getFieldValue }) => ({
                                                validator(_, value) {
                                                    if (!value || getFieldValue('newPassword') === value) {
                                                        return Promise.resolve();
                                                    }
                                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                                },
                                            }),
                                        ]}
                                    >
                                        <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
                                    </Form.Item>
                                    <Form.Item>
                                        <Button type="primary" htmlType="submit" loading={loading}>
                                            提交
                                        </Button>
                                    </Form.Item>
                                </Form>
                            </TabPane>

                            {/* 数据统计标签页 */}
                            <TabPane tab="数据统计" key="statistics">
                                <Row gutter={[16, 16]}>
                                    <Col span={8}>
                                        <Card>
                                            <Statistic 
                                                title="本月考勤" 
                                                value={22} 
                                                suffix="/ 22天" 
                                                valueStyle={{ color: '#3f8600' }}
                                            />
                                        </Card>
                                    </Col>
                                    <Col span={8}>
                                        <Card>
                                            <Statistic 
                                                title="本月迟到" 
                                                value={1} 
                                                suffix="次" 
                                                valueStyle={{ color: '#cf1322' }}
                                            />
                                        </Card>
                                    </Col>
                                    <Col span={8}>
                                        <Card>
                                            <Statistic 
                                                title="本月请假" 
                                                value={1} 
                                                suffix="天" 
                                                valueStyle={{ color: '#1890ff' }}
                                            />
                                        </Card>
                                    </Col>
                                </Row>
                                <Divider orientation="left">考勤统计</Divider>
                                <div style={{ height: 300, marginTop: 20 }}>
                                    <ResponsiveContainer width="100%" height="100%">
                                        <AreaChart
                                            data={attendanceData}
                                            margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
                                        >
                                            <CartesianGrid strokeDasharray="3 3" />
                                            <XAxis dataKey="month" />
                                            <YAxis />
                                            <Tooltip />
                                            <Area type="monotone" dataKey="attendance" stackId="1" stroke="#82ca9d" fill="#82ca9d" name="正常" />
                                            <Area type="monotone" dataKey="late" stackId="1" stroke="#ffc658" fill="#ffc658" name="迟到" />
                                            <Area type="monotone" dataKey="leave" stackId="1" stroke="#8884d8" fill="#8884d8" name="请假" />
                                            <Area type="monotone" dataKey="absent" stackId="1" stroke="#ff8042" fill="#ff8042" name="缺勤" />
                                        </AreaChart>
                                    </ResponsiveContainer>
                                </div>
                            </TabPane>
                        </Tabs>
                    </Card>
                </Col>
            </Row>
        </div>
    );
};

export default Profile;